import { User, Product, ApiResponse, PaginatedResponse, LoginForm, RegisterForm } from '../types';

// API 基础配置
const API_BASE_URL = process.env.REACT_APP_API_URL || 'https://jsonplaceholder.typicode.com';

class ApiService {
  private baseURL: string;

  constructor(baseURL: string = API_BASE_URL) {
    this.baseURL = baseURL;
  }

  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<ApiResponse<T>> {
    const url = `${this.baseURL}${endpoint}`;
    const config: RequestInit = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
      ...options,
    };

    // 添加认证token（如果存在）
    const token = localStorage.getItem('authToken');
    if (token) {
      config.headers = {
        ...config.headers,
        Authorization: `Bearer ${token}`,
      };
    }

    try {
      const response = await fetch(url, config);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      // 模拟标准API响应格式
      return {
        data,
        message: 'Success',
        success: true,
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      throw new Error(`API request failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  // 用户相关API
  async getUsers(): Promise<ApiResponse<User[]>> {
    return this.request<User[]>('/users');
  }

  async getUserById(id: number): Promise<ApiResponse<User>> {
    return this.request<User>(`/users/${id}`);
  }

  async createUser(userData: RegisterForm): Promise<ApiResponse<User>> {
    return this.request<User>('/users', {
      method: 'POST',
      body: JSON.stringify(userData),
    });
  }

  async updateUser(id: number, userData: Partial<User>): Promise<ApiResponse<User>> {
    return this.request<User>(`/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify(userData),
    });
  }

  async deleteUser(id: number): Promise<ApiResponse<void>> {
    return this.request<void>(`/users/${id}`, {
      method: 'DELETE',
    });
  }

  // 认证相关API
  async login(credentials: LoginForm): Promise<ApiResponse<{ user: User; token: string }>> {
    // 模拟登录API
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockUser: User = {
          id: 1,
          username: credentials.email.split('@')[0],
          email: credentials.email,
          firstName: 'John',
          lastName: 'Doe',
          role: 'user' as any,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        };

        resolve({
          data: {
            user: mockUser,
            token: 'mock-jwt-token-' + Date.now(),
          },
          message: 'Login successful',
          success: true,
          timestamp: new Date().toISOString(),
        });
      }, 1000);
    });
  }

  async register(userData: RegisterForm): Promise<ApiResponse<User>> {
    return this.createUser(userData);
  }

  // 产品相关API
  async getProducts(page: number = 1, limit: number = 10): Promise<ApiResponse<PaginatedResponse<Product>>> {
    // 模拟分页产品数据
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockProducts: Product[] = Array.from({ length: limit }, (_, index) => ({
          id: (page - 1) * limit + index + 1,
          name: `Product ${(page - 1) * limit + index + 1}`,
          description: `This is a description for product ${(page - 1) * limit + index + 1}`,
          price: Math.floor(Math.random() * 1000) + 10,
          category: ['Electronics', 'Clothing', 'Books', 'Home'][Math.floor(Math.random() * 4)],
          imageUrl: `https://picsum.photos/300/200?random=${(page - 1) * limit + index + 1}`,
          stock: Math.floor(Math.random() * 100) + 1,
          rating: Math.floor(Math.random() * 5) + 1,
          reviews: [],
          createdAt: new Date().toISOString(),
        }));

        resolve({
          data: {
            data: mockProducts,
            total: 100,
            page,
            limit,
            totalPages: Math.ceil(100 / limit),
          },
          message: 'Products fetched successfully',
          success: true,
          timestamp: new Date().toISOString(),
        });
      }, 500);
    });
  }

  async getProductById(id: number): Promise<ApiResponse<Product>> {
    return new Promise((resolve) => {
      setTimeout(() => {
        const categories = ['Electronics', 'Clothing', 'Books', 'Home', 'Sports', 'Beauty'];
        const productNames = [
          '智能手机', '笔记本电脑', '无线耳机', '智能手表', '平板电脑',
          '运动鞋', '休闲外套', '牛仔裤', '连衣裙', '背包',
          '编程指南', '设计思维', '商业管理', '历史文学', '科学探索',
          '咖啡机', '空气净化器', '台灯', '收纳盒', '植物盆栽'
        ];

        const mockReviews = [
          {
            id: 1,
            userId: 1,
            productId: id,
            rating: 5,
            comment: '非常满意的购买体验，产品质量很好，物流也很快！',
            createdAt: new Date(Date.now() - 86400000).toISOString(),
            user: {
              username: '张三',
              avatar: 'https://picsum.photos/40/40?random=1'
            }
          },
          {
            id: 2,
            userId: 2,
            productId: id,
            rating: 4,
            comment: '整体不错，性价比很高，推荐购买。',
            createdAt: new Date(Date.now() - 172800000).toISOString(),
            user: {
              username: '李四',
              avatar: 'https://picsum.photos/40/40?random=2'
            }
          },
          {
            id: 3,
            userId: 3,
            productId: id,
            rating: 5,
            comment: '超出预期的好产品，会继续关注这个品牌。',
            createdAt: new Date(Date.now() - 259200000).toISOString(),
            user: {
              username: '王五',
              avatar: 'https://picsum.photos/40/40?random=3'
            }
          }
        ];

        const mockProduct: Product = {
          id,
          name: productNames[(id - 1) % productNames.length],
          description: `这是一款精心设计的${productNames[(id - 1) % productNames.length]}，采用优质材料制作，具有出色的性能和耐用性。产品经过严格的质量检测，确保为用户提供最佳的使用体验。无论是日常使用还是专业需求，都能完美满足您的期待。我们承诺提供优质的售后服务，让您购买无忧。`,
          price: Math.floor(Math.random() * 1000) + 50,
          category: categories[Math.floor(Math.random() * categories.length)],
          imageUrl: `https://picsum.photos/400/300?random=${id}`,
          stock: Math.floor(Math.random() * 100) + 1,
          rating: Math.round((Math.random() * 2 + 3) * 10) / 10, // 3.0-5.0 rating
          reviews: mockReviews,
          createdAt: new Date(Date.now() - Math.random() * 30 * 86400000).toISOString(),
        };

        resolve({
          data: mockProduct,
          message: 'Product fetched successfully',
          success: true,
          timestamp: new Date().toISOString(),
        });
      }, 300);
    });
  }
}

export const apiService = new ApiService();
export default apiService;